
export function goNext(url, type) {

    let pages = getCurrentPages()//关于获取页面的官方文档https://uniapp.dcloud.io/api/window/window

    // console.log('层数',pages.length)

    if(pages.length > 9 ){

        uni.reLaunch({
            url
        });

        return
    } 

    
    if (type == 'switchTab') {
        uni.switchTab({
            url
        })
    } 
    //关闭所有的页面，打开某个页面
    else if (type == 'reLaunch') {
        uni.reLaunch({
            url
        });
    } 
    //关闭当前页
    else if (type == 'redirectTo') {
        uni.redirectTo({
            url
        })
    } else {
        uni.navigateTo({
            url,
            fail(err) {
                console.error('跳转错误',err)
            }
        })
    }
}

//获取图片
const newOssUrl = 'https://oss.qmxip.com/'

export const $getImg = (id, type) => {


    if (id && id != 'null') {

        if (id.indexOf("https") >= 0) {
            return id
        }

        var imgUrl = newOssUrl

        if(id.includes('transaction/')){
            imgUrl = 'https://qmxfile.oss-cn-zhangjiakou.aliyuncs.com/'
        }

        if (id.indexOf('tm_img') >= 0) {
            id = id.replace('.jpg', "")
        }

        

        if (type == 1) return `${imgUrl}${id}`   //最大的图
        if (type == 2) return `${imgUrl}${id}?x-oss-process=style/pc_trade_resize`   //  100*100
        if (type == 3) return `${imgUrl}${id}?x-oss-process=style/new-index`; // 560*350

        return `${imgUrl}${id}?xcx_good_resize`

    }

    return ""

}

export const $webImg = (id) => {

    return "http://192.168.8.10:8700/"+id

}


//自定义封装stroage过期时间
/**
 *key
 *val
 *time 默认单位为天 不传或者为0则没有超时时间
 */

export const Junstroge = {
    set(key, val, time) {
        let now = time ? (new Date().getTime() + time * 24 * 60 * 60 * 1000) : 0
        uni.setStorageSync(key, {
            val: val,
            t: now
        })
    },
    get(key) {
        let res = uni.getStorageSync(key);

        if (!(res instanceof Error)) {
            let now = new Date().getTime()

            if (res.t === 0 || res.t >= now) {
                return res.val
            } else {
                this.remove(key)
                return ''
            }
        } else {
            return ''
        }
    },
    remove(key) {
        uni.removeStorage({
            key: key,
            success: res => {}
        });
    }
}
/**
 * 深度克隆
 */

  function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach((keys) => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys])
        } else {
            targetObj[keys] = source[keys]
        }
    })
    return targetObj
}

//拨打电话
function takePhone( phone ){

    uni.makePhoneCall({
        phoneNumber:phone,
        success:function(){
            console.log('拨打电话成功');
        },
        fail() {
            console.log('打电话失败了');
        }
    })
}

//防重复点击

function preventRepeatClickOld() {

    var canRun = true;
    var countdown = 0
    return function (fn, time = 1000,noticeFn) {

        if (!canRun){
          noticeFn && noticeFn( countdown )
          return;
        }

        countdown = time

        let timer = setInterval(()=>{

          countdown -= 500

          if(countdown <= 0){

            clearInterval( timer )
          }

        },500)


        canRun = false;
        fn()
        setTimeout(() => {
            canRun = true;
        }, time)
    }

}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function () {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function (...args) {
        context = this
        timestamp = +new Date()
        const callNow = immediate && !timeout
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}

export const PageInit = function( $vm ){

    $vm.prototype.$goNext = goNext

    $vm.prototype.$getImg = $getImg
    $vm.prototype.$webImg = $webImg
    
    $vm.prototype.$Junstroge = Junstroge

    $vm.prototype.$deepClone = deepClone

    $vm.prototype.$takePhone = takePhone

    $vm.prototype.$preventRepeatClickOld =  new preventRepeatClickOld()

    $vm.prototype.$debounce = debounce


}

